#!/bin/bash


DEPLOY_BAG="app-deploy.tgz"

server_name=("hwtest" "appjavatest")

usage() {
    echo "Usage: $0 [server_name]"
    echo ""
    echo "server_name:"
    echo "  hwtest, appjavatest"
    echo ""
    echo "Example:"
    echo "  $0 hwtest"
    echo "  $0 appjavatest hwtest"
}

error() {
    echo -e "\033[31m[error] $1\033[0m"
}

warning() {
    echo -e "\033[33m$1\033[0m"
}

info() {
    echo -e "\033[32m$1\033[0m"
}

clean() {
    info "Step 1. Clean"
    echo ""

    gradle clean

    echo ""
}

build() {
    info "Step 2. Build"
    echo ""

    ./build.sh

    if [[ $? -ne 0 ]]; then
        error "Build failed..."
        exit 1
    fi

    echo ""
}

scp_file() {
    if [[ ! -f "${DEPLOY_BAG}" ]]; then
        error "${DEPLOY_BAG} not found"
        exit 1
    fi

    serverUrl="root@$1.linkdood.cn:$3"
    if [[ $1 == "appjavatest" ]]; then
        serverUrl="root@172.16.8.165:$3"
    fi
	
	if [[ $1 == "hwtest" ]]; then
        serverUrl="root@123.59.28.98:$3"
    fi

    info "Step: Push ${DEPLOY_BAG} to $serverUrl"
    echo ""

    sshpass -p $2 scp ${DEPLOY_BAG} $serverUrl
}

check_cmd() {
    if ! command -v sshpass >/dev/null 2>&1; then
        error "sshpass not found"
        exit
    fi
}

check_args() {
    for args in $@
    do
       if ! echo "${server_name[@]}" | grep -w "$args" &>/dev/null; then
           error "not support arg : $args"
           echo ""
           usage
           exit 1
       fi
    done
}

if [[ $# -eq 0 ]]; then
    usage
    exit
fi

check_cmd
check_args $@
#clean
#build

for args in $@
do
   case "$args" in
    hwtest)
        scp_file hwtest "Linkdood@123456" "/data/linkdood/apps/download/"
        ;;
   appjavatest)
        scp_file appjavatest "Linkdood@123456.300352" "/data/linkdood/apps/download/"
        ;;
    esac

    echo ""

    if [[ $? -ne 0 ]]; then
        error "scp war to server $args failed."
    fi
done


